<template>
  <div class="user-center-container">
    <!-- 用户信息卡片 -->
    <el-card class="user-info-card">
      <div class="user-info">
        <el-avatar :size="100" :src="userInfo.avatar">{{ userInfo.username }}</el-avatar>
        <div class="user-detail">
          <h2>{{ userInfo.username }}</h2>
          <p>{{ userInfo.email }}</p>
          <p>会员等级：<el-tag type="warning">{{ userInfo.level }}</el-tag></p>
        </div>
        <el-button type="primary" @click="editDialogVisible = true">编辑资料</el-button>
      </div>
    </el-card>

    <!-- 数据统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <i class="el-icon-shopping-bag-2 stat-icon" style="color: #409EFF"></i>
            <div>
              <div class="stat-value">{{ statistics.orders }}</div>
              <div class="stat-label">我的订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <i class="el-icon-star-off stat-icon" style="color: #E6A23C"></i>
            <div>
              <div class="stat-value">{{ statistics.favorites }}</div>
              <div class="stat-label">我的收藏</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <i class="el-icon-date stat-icon" style="color: #67C23A"></i>
            <div>
              <div class="stat-value">{{ statistics.reserves }}</div>
              <div class="stat-label">我的预约</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <i class="el-icon-coin stat-icon" style="color: #F56C6C"></i>
            <div>
              <div class="stat-value">¥{{ statistics.totalSpent }}</div>
              <div class="stat-label">累计消费</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 功能菜单 -->
    <el-card class="menu-card">
      <el-tabs v-model="activeTab">
        <!-- 我的订单 -->
        <el-tab-pane label="我的订单" name="orders">
          <el-table :data="orders" v-loading="loading">
            <el-table-column prop="orderNo" label="订单号"></el-table-column>
            <el-table-column prop="productName" label="商品/宠物"></el-table-column>
            <el-table-column prop="amount" label="金额">
              <template slot-scope="scope">
                <span class="price">¥{{ scope.row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleViewOrder(scope.row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 服务预约 -->
        <el-tab-pane label="服务预约" name="services">
          <el-table :data="serviceReserves" v-loading="loading">
            <el-table-column prop="serviceName" label="服务名称"></el-table-column>
            <el-table-column prop="petName" label="宠物"></el-table-column>
            <el-table-column prop="reserveDate" label="预约时间"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag :type="getReserveStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleViewService(scope.row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 寄养记录 -->
        <el-tab-pane label="寄养记录" name="foster">
          <el-table :data="fosterRecords" v-loading="loading">
            <el-table-column prop="petName" label="宠物名称"></el-table-column>
            <el-table-column prop="startDate" label="入住时间"></el-table-column>
            <el-table-column prop="endDate" label="离店时间"></el-table-column>
            <el-table-column prop="days" label="天数">
              <template slot-scope="scope">
                {{ scope.row.days }}天
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="费用">
              <template slot-scope="scope">
                <span class="price">¥{{ scope.row.totalPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag :type="getFosterStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleViewFoster(scope.row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 我的地址 -->
        <el-tab-pane label="收货地址" name="address">
          <el-button type="primary" size="small" @click="handleAddAddress" style="margin-bottom: 15px;">
            <i class="el-icon-plus"></i> 新增地址
          </el-button>
          <el-table :data="addresses">
            <el-table-column prop="contact" label="收货人"></el-table-column>
            <el-table-column prop="phone" label="联系电话"></el-table-column>
            <el-table-column prop="address" label="收货地址" show-overflow-tooltip></el-table-column>
            <el-table-column prop="isDefault" label="默认地址" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isDefault" type="success" size="small">默认</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text">编辑</el-button>
                <el-button size="mini" type="text" style="color: #F56C6C">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 编辑资料对话框 -->
    <el-dialog title="编辑个人资料" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUserInfo">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserInfo, updateProfile, getUserStatistics } from '@/api/user'
import { getOrderList } from '@/api/order'
import { getReservationList } from '@/api/service'
import { getFosterList } from '@/api/foster'
import { getAddressList } from '@/api/address'

export default {
  name: 'UserCenter',
  data () {
    return {
      userInfo: {},
      statistics: {
        orders: 0,
        favorites: 0,
        reserves: 0,
        totalSpent: 0
      },
      activeTab: 'orders',
      loading: false,
      orders: [],
      serviceReserves: [],
      fosterRecords: [],
      addresses: [],
      editDialogVisible: false,
      editForm: {
        username: '',
        email: '',
        phone: ''
      }
    }
  },
  created () {
    this.loadUserInfo()
    this.loadStatistics()
    this.loadOrders()
    this.loadServiceReserves()
    this.loadFosterRecords()
    this.loadAddresses()
  },
  methods: {
    loadUserInfo () {
      getUserInfo().then(res => {
        if (res && res.data) {
          this.userInfo = {
            username: res.data.username || res.data.realName,
            email: res.data.email || '',
            phone: res.data.phone || '',
            avatar: res.data.avatar || '',
            level: res.data.level || '普通会员'
          }
          this.editForm = { ...this.userInfo }
        }
      }).catch(err => {
        console.error('加载用户信息失败：', err)
        this.$message.error('加载用户信息失败')
      })
    },
    loadStatistics () {
      getUserStatistics().then(res => {
        if (res && res.data) {
          this.statistics = {
            orders: res.data.orders || 0,
            favorites: res.data.favorites || 0,
            reserves: res.data.reserves || 0,
            totalSpent: res.data.totalSpent || 0
          }
        }
      }).catch(err => {
        console.error('加载统计数据失败：', err)
      })
    },
    loadOrders () {
      getOrderList({ pageNum: 1, pageSize: 5 }).then(res => {
        if (res && res.data) {
          const list = res.data.records || res.data.list || res.data || []
          this.orders = list.map(item => ({
            id: item.id,
            orderNo: item.orderNo,
            productName: item.productName || '商品',
            amount: item.amount || item.totalAmount || 0,
            createTime: item.createTime,
            status: item.statusName || item.status
          }))
        }
      }).catch(err => {
        console.error('加载订单失败：', err)
      })
    },
    loadServiceReserves () {
      getReservationList({ pageNum: 1, pageSize: 5 }).then(res => {
        if (res && res.data) {
          const list = res.data.records || res.data.list || res.data || []
          this.serviceReserves = list.map(item => ({
            id: item.id,
            serviceName: item.serviceName || '服务',
            petName: item.petName || '宠物',
            reserveDate: item.reserveDate || item.reserveTime,
            status: item.statusName || item.status
          }))
        }
      }).catch(err => {
        console.error('加载预约记录失败：', err)
      })
    },
    loadFosterRecords () {
      getFosterList({ pageNum: 1, pageSize: 5 }).then(res => {
        if (res && res.data) {
          const list = res.data.records || res.data.list || res.data || []
          this.fosterRecords = list.map(item => ({
            id: item.id,
            petName: item.petName || '宠物',
            startDate: item.startDate,
            endDate: item.endDate,
            days: item.days || 0,
            totalPrice: item.totalPrice || item.totalAmount || 0,
            status: item.statusName || item.status
          }))
        }
      }).catch(err => {
        console.error('加载寄养记录失败：', err)
      })
    },
    loadAddresses () {
      getAddressList().then(res => {
        if (res && res.data) {
          const list = res.data.records || res.data.list || res.data || []
          this.addresses = list.map(item => ({
            id: item.id,
            contact: item.contact || item.receiver,
            phone: item.phone,
            address: item.address || (item.province + item.city + item.district + item.detail),
            isDefault: item.isDefault === 1 || item.isDefault === true
          }))
        }
      }).catch(err => {
        console.error('加载地址列表失败：', err)
      })
    },
    handleSaveUserInfo () {
      updateProfile(this.editForm).then(res => {
        this.$message.success('保存成功')
        this.editDialogVisible = false
        this.userInfo = { ...this.editForm }
      }).catch(err => {
        console.error('保存用户信息失败：', err)
        this.$message.error('保存失败')
      })
    },
    handleViewOrder (row) {
      // 这里将来对接接口 GET /api/order/detail/{id}
      this.$router.push({ path: '/user/order-detail', query: { id: row.id } })
    },
    handleViewService (row) {
      console.log('查看服务预约', row)
    },
    handleViewFoster (row) {
      this.$router.push({ path: '/user/foster-detail', query: { id: row.id } })
    },
    handleAddAddress () {
      this.$message.info('添加地址功能')
    },
    getOrderStatusType (status) {
      const typeMap = {
        '待付款': 'warning',
        '待发货': 'primary',
        '已发货': 'success',
        '已完成': 'info',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    },
    getReserveStatusType (status) {
      const typeMap = {
        '待确认': 'warning',
        '已确认': 'primary',
        '已完成': 'success',
        '已取消': 'info'
      }
      return typeMap[status] || 'info'
    },
    getFosterStatusType (status) {
      const typeMap = {
        '待确认': 'warning',
        '已确认': 'primary',
        '寄养中': 'success',
        '已完成': 'info',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.user-center-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.user-info-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 30px;
}

.user-detail {
  flex: 1;
}

.user-detail h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.user-detail p {
  margin: 5px 0;
  color: #666;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  font-size: 48px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #999;
  margin-top: 5px;
}

.menu-card {
  min-height: 400px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}
</style>
